<?php
if(isset($_POST['rowid']) && isset($_POST['billno'])&& isset($_POST['qty'])) {
    $rowid=$_POST['rowid'];
    $billno=$_POST['billno'];
    $qty=$_POST['qty'];
    $discount=$_POST['discount'];
    
        include '../../libraries/dbconfig.php';
           $dsc = mysql_query("select * from options");
    $dsc_data = mysql_fetch_array($dsc);
    $bill_detail=mysql_query("select productid,rate,qty from billdetails where rowid='$rowid'") or die(mysql_error());
        $bill_detail_data=mysql_fetch_array($bill_detail); 
        $rate=$bill_detail_data['rate'];
         $p_qty=$bill_detail_data['qty'];
          $productid=$bill_detail_data['productid'];
     
        if($qty !== $p_qty) {
    if($dsc_data['discount_type'] == "amount") {
        $vat=((($rate-$discount)/100)*14.5)*$qty;
        $totalrate=(($rate-$discount)*$qty);
        $final_discount=$discount*$qty;
        $total=$totalrate+$vat;
    }
    else {
        $temp_discount=($rate/100)*$discount;
        $final_discount=$temp_discount*$qty;
          $vat=((($rate-$temp_discount)/100)*14.5)*$qty;
        $totalrate=($rate-$temp_discount)*$qty;
        $total=$totalrate+$vat;
    }
       
    $bill_detail_update=mysql_query("Update billdetails set qty='$qty', discount='$final_discount', total='$total' where rowid = '$rowid'") or die(mysql_error());
 
   $bill_total=0;
   $bill_discount=0;
   $bill_vat=0;
      $bill_dt=mysql_query("select discount,vat,rate,total from billdetails where rowid='$rowid'") or die(mysql_error());
     while($bill_dt_data=mysql_fetch_array($bill_dt)) {
         $total=$bill_dt_data['total'];
         $discount=$bill_dt_data['discount'];
         $vat=$bill_dt_data['vat'];
         $bill_total=$bill_total+$total;
         $bill_discount=$bill_discount+$discount;
         $bill_vat=$bill_vat+$vat;
         
     } 
     echo $bill_total;
     echo "<br>";
     echo $bill_vat;
     echo "<br>";
     echo $bill_discount;
     echo "<br>";
     echo $billno;
    
 $bill_update=mysql_query("Update bills set discount='$bill_discount', amount='$bill_total', vat='$bill_vat' where billno = '$billno'") or die(mysql_error());
     if($qty > $p_qty) {
             $qtty=$qty-$p_qty;
          
 $invoice_update=mysql_query("Update invoicedetails set sold = sold + '$qtty'  where productid = '$productid'") or die(mysql_error());
       
         }
         else if($qty < $p_qty) {
              $qtty=$p_qty-$qty;
               $invoice_update=mysql_query("Update invoicedetails set sold = sold - '$qtty'  where productid = '$productid'") or die(mysql_error());
      
         }
        }
}
else {
    echo "Invalid Request";
}


?>